import { HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './User';


function userNameValidator(control: FormControl): {[s:string]:boolean}{
  if(!control.value.match(/^zime/)){
    return{invalidUser:true};
  }
  return{};
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  myForm:FormGroup;
  id:AbstractControl;
  name:AbstractControl;
  password: AbstractControl;
  newpassword:AbstractControl;
  users!:User[];
  baseUrl = 'http://127.0.0.1:8080/user/';
  
 

  constructor(private fb:FormBuilder,private httpClient:HttpClient){
    this.myForm = this.fb.group(
    {
      'id':[''],
      'name':['',Validators.compose([Validators.required,Validators.minLength(7),userNameValidator])],
      'password':['',Validators.compose([Validators.required,Validators.minLength(6)])],
      'newpassword':['']
    }
    );
    this.id = this.myForm.controls['id'];
    this.name = this.myForm.controls['name'];
    this.password = this.myForm.controls['password'];
    this.newpassword = this.myForm.controls['newpassword'];
  }
  ngOnInit(): void {

  }

  login() {
    this.httpClient.post('http://127.0.0.1:8080/user/login',
    this.myForm.value)
    .subscribe(
      res => { 
        console.log(res)
        var data = JSON.stringify(res);
        data=data.substring(27,31);
        alert(data);
      }
    )
  }

  add() {
    this.httpClient.post('http://127.0.0.1:8080/user/add',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        var data = JSON.stringify(res);
        data=data.substring(27,31);
        alert(data);
      }
    )
    
  }

  xiugai() {
    this.httpClient.post('http://127.0.0.1:8080/user/xiugai',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        var data = JSON.stringify(res);
        data=data.substring(27,31);
        alert(data);
      }
    )
  }

  delete() {
    this.httpClient.post('http://127.0.0.1:8080/user/delete',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        var data = JSON.stringify(res);
        data=data.substring(27,31);
        alert(data);
      }
    )
  }

  onSubmit(){
    this.httpClient.get('http://127.0.0.1:8080/user/').subscribe(
      (res : any) => {
        this.users = res.data
      }
    )
    }

    logout(){
      this.httpClient.post('http://127.0.0.1:8080/user/logout',
      this.myForm.value)
      .subscribe(
        res => { 
          console.log(res)
          alert("退出成功");
        }
      )
    }
}